package com.erbao.dp.composite;

import java.util.LinkedList;
import java.util.List;

/**
 * @author CaoBaoYin
 * @since 21/9/16 16:30
 */
public class Main {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");
        LeafNode c11 = new LeafNode("c11");
        LeafNode c12 = new LeafNode("c12");
        BranchNode chapter21 = new BranchNode("chapter21");
        LeafNode c211 = new LeafNode("c211");
        LeafNode c212 = new LeafNode("c212");

        root.add(chapter1);
        root.add(chapter2);

        chapter1.add(c11);
        chapter1.add(c12);

        chapter2.add(chapter21);
        chapter21.add(c211);
        chapter21.add(c212);

        printNode(root, 0);
    }

    private static void printNode(Node root, int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("--");
        }
        root.print();
        if (root instanceof BranchNode) {
            depth++;
            for (Node node : ((BranchNode)root).nodeList) {
                printNode(node, depth);
            }
        }
    }
}
abstract class Node{
    abstract public void print();
}
class LeafNode extends Node{
    String content;

    public LeafNode(String content) {
        this.content = content;
    }

    @Override
    public void print() {
        System.out.println(content);
    }
}

class BranchNode extends Node{
    List<Node> nodeList = new LinkedList<>();

    String name;

    public BranchNode(String name) {
        this.name = name;
    }

    public boolean add (Node node){
        return nodeList.add(node);
    }

    @Override
    public void print() {
        System.out.println(name);
    }
}